using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;

namespace Office.Utility.Toolbar
{
    public sealed class ToolbarComboBox : ToolbarControl
	{
		private MSOffice.MsoComboStyle _style = MSOffice.MsoComboStyle.msoComboNormal;
		private readonly List<string> _items = new List<string>();

        public MSOffice.MsoComboStyle Style
		{
			get { return _style; }
			set { _style = value; }
		}

        public int DropDownLines { get; set; }

        public IList<string> Items
		{
			get { return _items; }
		}

		public event EventHandler<ToolbarComboBoxEventArgs> Change;

		public ToolbarComboBox(string id)
			: base(id)
		{
		}

		public ToolbarComboBox(string id, MSOffice.MsoComboStyle style)
			: base(id)
		{
			_style = style;
		}

		public ToolbarComboBox(string id, string caption, MSOffice.MsoComboStyle style)
			: base(id, caption)
		{
			_style = style;
		}

		public ToolbarComboBox(string id, string caption, string tooltip, MSOffice.MsoComboStyle style)
			: base(id, caption, tooltip)
		{
			_style = style;
		}


		internal override void Attach(MSOffice.CommandBar bar, WindowAdapter window)
		{
			var cbo = FindControl<MSOffice.CommandBarComboBox>(bar);

			if (cbo == null)
			{
				cbo = (MSOffice.CommandBarComboBox)bar.Controls.Add(
					MSOffice.MsoControlType.msoControlComboBox,
					Type.Missing, Type.Missing,
					Position != null ? Position.Value : Type.Missing, true);

				cbo.Parameter = Id;
				cbo.Tag = Guid.NewGuid().ToString();
			}

			cbo.Caption = Caption;
			cbo.TooltipText = ToolTip;
			cbo.Style = Style;
			cbo.DropDownLines = DropDownLines;

			foreach (var s in _items)
				cbo.AddItem(s, Type.Missing);

			cbo.Change += delegate(MSOffice.CommandBarComboBox ctrl)
			{
				var args = new ToolbarComboBoxEventArgs(window, bar, ctrl.ListIndex - 1);
                //Use CommandBarManager's DynamicInvoke to ensure this event fires on the right thread
                CommandBarManager.DynamicInvoke(Change, this, args);
			};

			AddControl(cbo);
			window.Close += ((sender, args) => RemoveControl(cbo));
		}
	}
}
